package com.alfayun.fiscalriskanalysis.enterprise;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alfayun.fiscalriskanalysis.common.HttpBadRequestException;
import com.alfayun.fiscalriskanalysis.common.HttpNotFoundException;

@Controller
@RequestMapping("/client/enterprise")
public class EnterpriseController {
	
	@Autowired
	private EnterpriseService service;
	
	@GetMapping("/list")
	public String list() {
		return "client/enterprise";
	}
	
	@ResponseBody
	@GetMapping("/list/data")
	public Map<String, List<Enterprise>> listData() {
		Map<String, List<Enterprise>> map = new HashMap<>();
		map.put("data", service.list());
		return map;
	}
	
	@ResponseBody
	@GetMapping("/queryById/{id}")
	public Enterprise queryById(@PathVariable int id) throws HttpNotFoundException {
		try {
			return service.queryById(id);
		} catch (NoSuchEnterpriseException e) {
			throw HttpNotFoundException.build(e);
		}
	}
	
	@ResponseBody
	@RequestMapping("/add")
	public Enterprise newEnterprise(@RequestBody Enterprise enterprise) {
		return service.newEnterprise(enterprise);
	}
	
	@ResponseBody
	@DeleteMapping("/delete/{id}")
	public void deleteEnterprise(@PathVariable int id) {
		service.deleteEnterprise(id);
	}

	@ResponseBody
	@PutMapping("/update/{id}")
	public Enterprise modifyEnterprise(@PathVariable int id, @RequestBody Enterprise enterprise)
			throws HttpNotFoundException, HttpBadRequestException {
		if (id == enterprise.getId()) {
			try {
				return service.modifyEnterprise(id, enterprise);
			} catch (NoSuchEnterpriseException e) {
				throw HttpNotFoundException.build(e);
			}
		}

		throw HttpBadRequestException.build(
				String.format("The id in the path(%d) and body(%d) does not match.", id, enterprise.getId()));
	}
	
	@ResponseBody
	@GetMapping("/dataForSelect2")
	public Map<String, List<Map<String, String>>> dataForSelect2() {
		Map<String, List<Map<String, String>>> results = new HashMap<>();
		List<Map<String, String>> list = new ArrayList<>();
		service.list().forEach(item -> {
			Map<String, String> map = new HashMap<>();
			map.put("id", item.getId().toString());
			map.put("text", item.name);
			list.add(map);
		});
		results.put("results", list);
		return results;
	}

}
